<template>
  <view class="drawer-content">
    <view
      :class="['drawer-content-drag', { 'drawer-content-init': state.initStatus }]"
      :style="state.transition + 'top:' + (state.dragTop + 'px')"
      :data-top="state.dragTop"
    >
      <view
        v-if="!state.initStatus"
        class="drag-handle"
        :style="'height:' + dragHandleHeight + 'px;'"
        @touchstart="drag_start"
        @touchmove.stop="drag_move"
        @touchend="drag_end"
        @touchcancel="drag_end"
      >
        <view class="drag-handle-line"></view>
      </view>
      <view
        id="drag-content"
        class="drag-content"
        :style="{ background: state.initStatus ? '#fff' : '' }"
      >
        <view class="pop-box" v-if="!state.initStatus">
          <view        
          @touchstart="drag_start"
          @touchmove.stop="drag_move"
          @touchend="drag_end"
          @touchcancel="drag_end">
            <p class="kilometer" v-if="!state.toTop">
              <span class="kilometer-num">{{runMileage}}</span>公里
            </p>
            <view :class="['time-box', { 'timedrop-box': state.toTop }]">
              <view class="distance item-con" v-if="state.toTop">
                <p class="num">{{runMileage}}</p>
                <p class="desc">总距离</p>
              </view>
              <view class="time item-con">
                <p class="num">{{ timerNum }}</p>
                <p class="desc">总时长</p>
              </view>
              <view class="speed item-con">
                <p class="num">{{matchSpeed}}</p>
                <p class="desc">实时配速</p>
                <!-- （总分钟/总公里） -->
              </view>
            </view>
          </view>
          <!-- <view class="btn-wrap" v-if="!state.toTop">
            <image class="suo-kai" src="../../static/icon-suoping-kai.png"></image>
          </view> -->
          <view class="btn-box" v-if="!state.toTop">
            <image class="icon-voice" :src="state.isPlay ? bofangImg : guanbiImg" @tap="handlePlayStatus"></image>
            <view style="display: flex;" v-if="runType === 'suspend' || runType === 'end'">
              <image
                class="btn-img"
                mode="aspectFill"
                src="../../static/icon-play.png"
                @tap="handleRestartRun"
              ></image>
            </view>
            <image
              v-if="runType === 'start' || runType === 'reStart'"
              class="btn-img"
              mode="aspectFill"
              src="../../static/icon-suspend.png"
              @tap="handleSuspend"
            ></image>
            <Prosess ref="processRef" @onTouchEndCb="getLongEndVal"></Prosess>
          </view>
        </view>
        <view class="pop-init" v-else>
          <view class="pop-position">
            <p class="position">廊坊市体育场</p>
            <!-- <p class="pos-kilometer">单圈约400米</p> -->
            <!-- <p>天气：晴</p> -->
          </view>
          <view class="position-btn">
            <view class="mileage" @tap="gotoPage('/pages/record/record')">
              <image class="mileage-icon" src="../../static/licheng.png"></image>
              <view> 里程记录 </view>
            </view>
            <view class="start-btn" @tap="handleStartRun"> 开始 </view>
            <view class="reward" @tap="gotoPage('/pages/reward/reward')">
              <image class="mileage-icon" src="../../static/jiangli.png"></image>
              <view> 活动说明 </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <uni-popup ref="alertDialogFileRef" type="dialog">
      <uni-popup-dialog
        :cancelText="state.cancelText"
        :confirmText="state.confirmText"
        :content="state.content"
        @close="handleClose"
        @confirm="gotoPage('/pages/personInfo/personInfo')"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script setup name="BottomDrawer">
import { onLaunch, onLoad, onShow, onHide, onUnload } from "@dcloudio/uni-app";
import {
  reactive,
  ref,
  toRefs,
  watch,
  onMounted,
  onUnmounted,
  getCurrentInstance,
} from "vue";
import * as API from "../../api/api"
import Prosess from "../components/prosess"
import { storeToRefs } from "pinia";
import { useRunInfoStore } from "../../store/runInfo";
import { useChatStore } from "../../store/chat"
import { useAppStore } from "../../store/app";
import bofangImg from '../../static/bofang.png';
import guanbiImg from '../../static/guanbi.png';
const useChatData = useChatStore()
const useAppData = useAppStore()
const useRunInfoData = useRunInfoStore();
const { proportionShow, initStatus, timerNum, centerDistance, runType, isShowCountdown, runMileage, matchSpeed, totalSeconds, sportRange, runUuid, isClickStatRun, recordEnd } = storeToRefs(
  useRunInfoData
);
const { sseEnd } = storeToRefs(useChatData)
const appInstance = getCurrentInstance().proxy;
let plugin = requirePlugin("WechatSI");
let manager = plugin.getRecordRecognitionManager();
const props = defineProps({
  dragHandleHeight: {
    type: Number,
    default: 20,
  },
  // proportionShow: { //显示比例，宽度的比例
  //   type: Number,
  //   default: 0.7, // 0.35
  // }
});

const { dragHandleHeight } = toRefs(props);
const processRef = ref(null)
const state = reactive({
  longEnd: false,
  cancelText: "取消",
  confirmText: "去填写",
  content: "开始跑步前，需填写个人资料",
  proportionShow: 0.7,
  initStatus: true,
  src: "../../static/logo.png",
  startY: 0,
  foldHeight: 0, //折叠的高度 通过proportionShow比例计算
  dragTop: -dragHandleHeight.value,
  top: 0,
  transition: "transition: top 0.1s;",
  windowHeight: "",
  windowWidth: "",
  toTop: true,
  userInfo: null,
  timer: null,
  animationType: "false",
  animation: null,
  progress: null,
  isPlay: true,
  innerAudioContext: null,
  countDownNum: 2,
  bbTimer: null
});

const alertDialogFileRef = ref(null);

const speechSynthesis = (content) => {
  plugin.textToSpeech({
    lang: "zh_CN",
    tts: true,
    speed: 0,
    content: content,
    success: function(res) {
      if (content === "GO") {
        clearInterval(state.bbTimer)
      }
      let music = null;
      music = uni.createInnerAudioContext(); //创建播放器对象
      music.src = res.filename;
      music.play(); //执行播放
      music.onEnded(() => {
        music = null;
      });
    },
    fail: function(res) {
      console.log("语音播放失败")
    }
  })
}

const handleSpeechPlay = () => {
  if (!state.isPlay) return
  speechSynthesis("叁")
  state.bbTimer = setInterval(() => {
    state.countDownNum--
    if (state.countDownNum < 0) {
      state.countDownNum = "GO"
    }
    let numStr = "贰"
    if (Number(state.countDownNum)+1 === 2) {
      numStr = "贰"
    }
    if (Number(state.countDownNum)+1 === 1) {
      numStr = "壹"
    }
    let content = state.countDownNum === "GO" ? "GO" : numStr
    speechSynthesis(content)
  }, 1000)
}


const getLongEndVal = (value) => {
  console.log('getLongEndVal', value)
  if (state.isPlay) {
    let content = "结束运动，恭喜你完成本次打卡！"
    speechSynthesis(content)
  }
}

const handlePlayStatus = () => {
  if (isShowCountdown.value) return
  state.isPlay = !state.isPlay
  let tipTxt = state.isPlay ? "声音已开启" : "声音已关闭"
  uni.showToast({
    title: tipTxt,
    icon: "none"
  })
  updateBroadcast()
}

// 更新语音配置
const updateBroadcast = () => {
  let params = {
    userId: state.userInfo?.customers?.customerId, 
    switchOff: state.isPlay ? 1 : 0
  }
  API.broadcastUpdate(params).then(res => {
    if(res.code === 0) {
      console.log("语音配置更新成功")
    }
  }).catch(err => {
    console.log("更新配置err", err)
  })
}

// 获取语音配置
const getBroadcast = () => {
  API.broadcastGet(state.userInfo?.customers?.customerId).then(res => {
    if(res.code === 0) {
      state.isPlay = res.data.switchOff == 1 ? true : false
    }
  }).catch(err => {
    console.log("获取配置err", err)
  })
}

const callChildMethod = () => {
  if (processRef.value) {
    processRef.value.upDateImgCb();
  }
};

const gotoPage = (url) => {
  uni.navigateTo({
    url,
  });
};

// 弹窗关闭
const handleClose = () => {
  console.log("弹窗关闭")
}

const handleAlertDialog = () => {
  state.cancelText = "取消";
  state.confirmText = "去填写";
  state.content = "开始跑步前，需填写个人资料";
  alertDialogFileRef?.value?.open();
};

const handleSuspend = () => {
  useRunInfoData.endTask('suspend')    
  let params = {
    timeType: 1, 
    uuid: runUuid.value,
    duration: totalSeconds.value,
    distance: runMileage.value,
    pace: matchSpeed.value
  }
  useChatData.getRobotMsg(params)
}

const handleRestartRun = () => {
  // if (recordEnd.value) {
  //   uni.showToast({
  //     title: "你已结束本次运动，无法继续跑步",
  //     icon: "none"
  //   })
  //   return
  // }
  useChatData.setShowContent(false)
  useChatData.setAllContent("")
  useRunInfoData.startTask('reStart', true)
}

const handleStartRun = () => {
  if (!isClickStatRun.value || !sseEnd.value) return
  useRunInfoData.setIsClickStartRun(false)
  if (!state.userInfo?.customers?.customerName || 
      !state.userInfo?.customers?.height ||
      !state.userInfo?.customers?.weight ||
      !state.userInfo?.customers?.emergencyContactMoblie ||
      !state.userInfo?.customers?.age ||
      !state.userInfo?.customers?.gender
  ) {
    handleAlertDialog();
    return;
  }
  useChatData.setShowContent(false)
  useChatData.setAllContent("")
  useRunInfoData
    .onStartRun()
    .then((res) => {
      useRunInfoData.startTask("start", true);
      useAppData.getAppSize().then(appRes => {
        console.log("appres", appRes, res)
        let params = {
          mileageUuid: res.data,
          brand: appRes.brand, 
          model: appRes.model, 
          wechatVersion: appRes.version, 
          systemVersion: appRes.system, 
          sdkVersion: appRes.SDKVersion
        }
        useAppData.onBurialPointTel(params)
      })
    })
    .catch((err) => {
      console.log(err);
    });
  handleSpeechPlay()
};

const drag_start = (event) => {
  if (isShowCountdown.value) return
  state.transition = "";
  state.top = event.currentTarget.dataset.top;
  state.startY = event.touches[0].clientY;
  console.log("拖拽开始", state.top, state.startY);
};
const drag_move = (event) => {
  // console.log(event.currentTarget)
  console.log("拖拽中", event.currentTarget);
  var len = event.touches[0].clientY - state.startY;
  var temp = state.top + len;
  if (temp >= dragHandleHeight.value) {
    temp = dragHandleHeight.value;
  }
  state.toTop = len < 0;

  const query = uni.createSelectorQuery().in(state);
  query
    .select("#drag-content")
    .boundingClientRect((data) => {
      if (temp <= 0 - data.height - dragHandleHeight.value) {
        temp = 0 - data.height - dragHandleHeight.value;
      }
      if (temp <= 0 - state.windowHeight * 0.8 - dragHandleHeight.value) {
        temp = 0 - state.windowHeight * 0.8 - dragHandleHeight.value;
      }
      state.dragTop = temp;
    })
    .exec();
  return false;
};
const drag_end = (event) => {
  if (isShowCountdown.value) return
  state.transition = "transition: top 0.3s;";
  const query = uni.createSelectorQuery().in(appInstance);
  query
    .select("#drag-content")
    .boundingClientRect((data) => {
      if (state.toTop) {
        state.dragTop = 0 - data.height - 20;
        setTimeout(() => {
          state.toTop = false;
        }, 0);
      } else {
        state.dragTop = -dragHandleHeight.value - state.foldHeight;
        setTimeout(() => {
          state.toTop = true;
        }, 0);
      }
    })
    .exec();
  return false;
};

const initDragTop = () => {
  const { windowWidth, windowHeight } = uni.getSystemInfoSync();
  state.windowWidth = windowWidth;
  state.windowHeight = windowHeight;
  state.foldHeight = state.windowWidth * proportionShow.value;
  state.dragTop = -dragHandleHeight.value - state.foldHeight;
};

onMounted(() => {
  initDragTop();
});

onLoad(() => {

})

onShow(() => {
  console.log("地图弹窗状态", initStatus.value, proportionShow.value);
  if (!useRunInfoData.isRuning) {
    if (initStatus.value) {
      useRunInfoData.setProportionShow(0.7);
    } else {
      useRunInfoData.setProportionShow(0.35);
    }
  } else {
    state.initStatus = false
    useRunInfoData.setProportionShow(0.35);
  }
  state.userInfo = uni.getStorageSync("userInfo")
    ? JSON.parse(uni.getStorageSync("userInfo"))
    : null;
  getBroadcast()
});

onUnload(() => {
  console.log("地图弹窗页面卸载");
  if (!useRunInfoData.isRuning) {
    useRunInfoData.setProportionShow(0.7);
    useRunInfoData.setInitStatus(true);
  }
  clearInterval(state.bbTimer)
});

watch(
  () => proportionShow.value,
  (newValue, oldValue) => {
    initDragTop();
  },
  { imediate: true }
);

watch(
  () => initStatus.value,
  (newValue, oldValue) => {
    console.log("初始状态", newValue);
    state.initStatus = newValue;
    useRunInfoData.setInitStatus(state.initStatus);
    // state.dragTop = -dragHandleHeight.value - state.foldHeight;
    if (!state.initStatus) {
      setTimeout(() => {
        state.toTop = true;
      }, 0);
    } else {
      console.log("地图初始状态")
      useRunInfoData.stopCountDown()
    }
  },
  { imediate: true }
)

watch(
  () => isShowCountdown.value,
  (newValue, oldValue) => {
    if(!newValue) {
      console.log("计时器结束")
      state.toTop = false
      const query = uni.createSelectorQuery().in(appInstance);
      query
      .select("#drag-content")
      .boundingClientRect((data) => {
        state.dragTop = 0 - data.height - 20;
      })
      .exec();
    }
  },
  { imediate: true }
);
defineExpose({
  callChildMethod
})
</script>

<style lang="scss">
.pop-box {
  position: relative;
  height: 890rpx;
}
.pop-init {
  height: 592rpx;
  background: #fff;
  border-radius: 48rpx 48rpx 0rpx 0rpx;
  padding: 56rpx;
  box-sizing: border-box;
  color: #222222;
  .pop-position {
    .position {
      font-weight: 500;
      font-size: 40rpx;
    }
    .pos-kilometer {
      font-weight: 400;
      font-size: 32rpx;
    }
  }
  .position-btn {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 28rpx;
    margin-top: 64rpx;
    text-align: center;
    .mileage-icon {
      width: 48rpx;
      height: 48rpx;
    }
    .start-btn {
      width: 208rpx;
      height: 208rpx;
      background: linear-gradient(151deg, #dbffdc 0%, #0df1ab 54%, #08cb8f 100%);
      border-radius: 100%;
      font-weight: 600;
      font-size: 58rpx;
      color: #ffffff;
      text-align: center;
      line-height: 208rpx;
    }
  }
}
.drawer-content {
  bottom: 0;
  left: 0;
  position: fixed;
  width: 100vw;
  color: #fff;
  .kilometer {
    margin-left: 64rpx;
    font-weight: 500;
    font-size: 48rpx;
    .kilometer-num {
      font-family: AlibabaPuHuiTiB;
      font-size: 170rpx;
    }
  }

  .time-box {
    display: flex;
    font-size: 68rpx;
    padding: 30rpx 0 0 64rpx;
    .item-con {
      width: 100%;
    }
    .num {
      font-family: AlibabaPuHuiTiB;
    }
    .desc {
      font-size: 32rpx;
      color: #dcdade;
    }
  }

  .timedrop-box {
    padding: 30rpx 72rpx 0;
    box-sizing: border-box;
    // justify-content: space-between;
    // margin: 30rpx 0 0 0;
    .speed,
    .distance,
    .time {
      text-align: center;
    }
    .num {
      font-family: AlibabaPuHuiTiB;
      font-size: 52rpx;
    }
  }
  .btn-wrap{
    width: 100vw;
    position: relative;
    .suo-kai{
      width: 80rpx;
      height: 80rpx;
      position: absolute;
      left: 36rpx;
      top: 50%;
      transform: translateY(-50%);
    }
  }
  .btn-box {
    display: flex;
    position: absolute;
    bottom: 50px;
    left: 50%;
    transform: translateX(-50%);
    .icon-voice{
      width: 80rpx;
      height: 80rpx;
      position: absolute;
      top: 50%;
      left: -60px;
      transform: translateY(-50%);
    }
    .btn-img {
      width: 180rpx;
      height: 180rpx;
      margin-right: 64rpx;
    }
  }
}

.drag-handle {
  height: 20px;
  width: 100vw;
  background-color: #463e4d;
  border-radius: 15px 15px 0 0;
  color: #eee;
  font-weight: bold;
  font-size: 20px;
  line-height: 1px;
  display: flex;
  justify-content: center;
  align-items: center;

  .drag-handle-line {
    width: 60rpx;
    height: 8rpx;
    margin-top: 10rpx;
    background: #635e6b;
    border-radius: 4rpx;
  }
}

.drawer-content-drag {
  background: #463e4d;
  position: absolute;
  height: 60vh;
  max-height: 80vh;
  width: 100vw;
  left: 0;
  border-radius: 48rpx 48rpx 0rpx 0rpx;
}

.drag-content {
  background: #463e4d;
  height: auto;
  max-height: 80vh;
  border-radius: 48rpx 48rpx 0rpx 0rpx;
}
.drag-content-init,
.drawer-content-init {
  background: #fff;
}
</style>
